package model

import (
	"context"
	"database/sql"
	"fmt"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ UmsRoleResourceRelationModel = (*customUmsRoleResourceRelationModel)(nil)

type (
	// UmsRoleResourceRelationModel is an interface to be customized, add more methods here,
	// and implement the added methods in customUmsRoleResourceRelationModel.
	UmsRoleResourceRelationModel interface {
		umsRoleResourceRelationModel
		Trans(ctx context.Context, fn func(ctx context.Context, session sqlx.Session) error) error
		RowBuilder() squirrel.SelectBuilder
		CountBuilder(field string) squirrel.SelectBuilder
		DeleteByRoleId(ctx context.Context, roleId int64) error
	}

	customUmsRoleResourceRelationModel struct {
		*defaultUmsRoleResourceRelationModel
	}
)

// NewUmsRoleResourceRelationModel returns a model for the database table.
func NewUmsRoleResourceRelationModel(conn sqlx.SqlConn, c cache.CacheConf) UmsRoleResourceRelationModel {
	return &customUmsRoleResourceRelationModel{
		defaultUmsRoleResourceRelationModel: newUmsRoleResourceRelationModel(conn, c),
	}
}

func (m *customUmsRoleResourceRelationModel) DeleteByRoleId(ctx context.Context, roleId int64) error {
	umsRoleResourceRelationIdKey := fmt.Sprintf("%s%v", cacheUmsRoleResourceRelationIdPrefix, roleId)
	_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("delete from %s where `role_id` = ?", m.table)
		return conn.ExecCtx(ctx, query, roleId)
	}, umsRoleResourceRelationIdKey)
	return err
}

// export logic
func (m *defaultUmsRoleResourceRelationModel) Trans(ctx context.Context, fn func(ctx context.Context, session sqlx.Session) error) error {
	return m.TransactCtx(ctx, func(ctx context.Context, session sqlx.Session) error {
		return fn(ctx, session)
	})

}

// export logic
func (m *defaultUmsRoleResourceRelationModel) RowBuilder() squirrel.SelectBuilder {
	return squirrel.Select(umsRoleResourceRelationRows).From(m.table)
}

// export logic
func (m *defaultUmsRoleResourceRelationModel) CountBuilder(field string) squirrel.SelectBuilder {
	return squirrel.Select("COUNT(" + field + ")").From(m.table)
}

// export logic
func (m *defaultUmsRoleResourceRelationModel) SumBuilder(field string) squirrel.SelectBuilder {
	return squirrel.Select("IFNULL(SUM(" + field + "),0)").From(m.table)
}
